package com.exchange.framework.aspectj;

import com.exchange.common.annotation.DataSource;
import com.exchange.common.config.datasource.DynamicDataSourceContextHolder;
import com.exchange.common.utils.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Order(1)
@Component
public class DataSourceClassAspect {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    //
    @Pointcut("@within(com.exchange.common.annotation.DataSource)")
    public void classPointCut(){

    }

    @Around("classPointCut()")
    public Object getSomething(ProceedingJoinPoint point) throws Throwable{

        Class aClass = Class.forName(point.getSignature().getDeclaringTypeName());
        DataSource dataSource = (DataSource) aClass.getAnnotation(DataSource.class);
        if (StringUtils.isNotNull(dataSource))
        {
            DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
        }

        try
        {
            return point.proceed();
        }
        finally
        {
            // 销毁数据源 在执行方法之后
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }
}

